﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Omu.ValueInjecter;
using Peninsula.Utility.ValueCopy.Convention;

namespace Peninsula.Utility.Helper
{

    public static class ValueCopyHelper
    {
        #region 复制属性（反射实现）

        /// <summary>
        /// 将对象属性赋值到实体中，只复制基本类型（反射实现）
        /// </summary>
        public static void CopyProperty<T, V>(T entity, V value, params string[] exFieldNames)
        {
            CopyProperty(entity, value, true, exFieldNames);
        }

        /// <summary>
        /// 将对象属性赋值到实体中，只复制基本类型（反射实现）
        /// </summary>
        public static void CopyProperty<T, V>(T entity, V value, bool isExclude, params string[] fields)
        {
            var targetProps = typeof(T).GetProperties();
            var valueProps = typeof(V).GetProperties();

            foreach (PropertyInfo targetPi in targetProps)
            {
                if (fields.Contains(targetPi.Name) != isExclude
                    && targetPi.CanRead && targetPi.CanWrite && targetPi.GetGetMethod() !=null 
                    && (targetPi.PropertyType == typeof(string)
                    || targetPi.PropertyType == typeof(bool)
                    || targetPi.PropertyType == typeof(decimal)
                    || targetPi.PropertyType == typeof(double)
                    || targetPi.PropertyType == typeof(float)
                    || targetPi.PropertyType == typeof(int)
                    || targetPi.PropertyType == typeof(byte)
                    || targetPi.PropertyType == typeof(DateTime)
                    || targetPi.PropertyType == typeof(bool?)
                    || targetPi.PropertyType == typeof(int?)
                    || targetPi.PropertyType == typeof(decimal?)
                    || targetPi.PropertyType == typeof(double?)
                    || targetPi.PropertyType == typeof(float?)
                    || targetPi.PropertyType == typeof(byte?)
                    || targetPi.PropertyType == typeof(DateTime?)
                    || targetPi.PropertyType.IsEnum))
                {
                    try
                    {
                        var valuePi = valueProps.FirstOrDefault(p => p.Name == targetPi.Name);
                        if (valuePi != null)
                        {
                            targetPi.SetValue(entity, valuePi.GetValue(value, null), null);
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }

        #endregion

        #region 复制属性（Value Injecter实现）
        
        public static void InjectProperty<T, V>(T entity, V value, params string[] ignoredPropsfields)
        {
            entity.InjectFrom(new BaseTypeInjection(ignoredPropsfields), value);
        }

        #endregion
    }
}
